package leetcode.median;

import leetcode.base.TreeNode;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * ClassName: $652_FindDuplicateSubtrees
 * Description:
 * date: 2021-12-07 17:00
 *
 * @author liyifan
 */
public class $652_FindDuplicateSubtrees {

    HashMap<String, Integer> countMap = new HashMap<>();
    List<TreeNode> res = new ArrayList<>();
    public List<TreeNode> findDuplicateSubtrees(TreeNode root) {
        recur(root);
        return res;
    }

    public String recur(TreeNode root){
        if (root == null)
            return "#";
        String left = recur(root.left);
        String right = recur(root.right);
        String thisTree = root.val + "," + left + "," + right;

        int times = countMap.getOrDefault(thisTree, 0);
        if (times == 1) {
            res.add(root);
        }
        countMap.put(thisTree, times + 1);
        return thisTree;
    }
}
